package me.wang.qrcodepay;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static me.wang.qrcodepay.QRcodePay.plugin;

public class CheckPayment {

    private final String API_URL;
    private final String PID;
    private final String KEY;
    private final String order;
    private String result;

    public String getResponse(){
        return this.result;
    }

    public CheckPayment(String order){
        this.API_URL = plugin.getConfig().getString("check_url");
        this.PID = plugin.getConfig().getString("pid");
        this.KEY = plugin.getConfig().getString("key");
        this.order = order;
        send();
    }

    private void send() {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("act", "order");
            params.put("pid", PID);
            params.put("key", KEY);
            params.put("out_trade_no", order);
            String requestUrl = buildGetRequestUrl(API_URL, params);
            String response = sendGetRequest(requestUrl);
            result = response;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static String buildGetRequestUrl(String baseUrl, Map<String, String> params) {
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        urlBuilder.append("?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (urlBuilder.charAt(urlBuilder.length() - 1) == '&') {
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        return urlBuilder.toString();
    }

    private static String sendGetRequest(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }
        return response.toString();
    }
}
